package com.sergenis.miniapp.jpanel_imagenfondo;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

/**
 * @author Ser Genis
 */
public class ImagePanel extends JPanel {
	private static final long	serialVersionUID	= 382877529556707398L;
	
	public ImagePanel() {
		this(null);
	}
	
	public ImagePanel(Image backgoundImage) {
		setOpaque(false);
		setBorder(new EmptyBorder(5, 5, 5, 5));
		this.backgoundImage = backgoundImage;
	}
	
	private java.awt.Image	backgoundImage;
	private ImageScale		imageScale	= ImageScale.CENTRE;
	
	public java.awt.Image getBackgoundImage() {
		return backgoundImage;
	}
	
	public void setBackgoundImage(java.awt.Image backgoundImage) {
		java.awt.Image oldValue = this.backgoundImage;
		this.backgoundImage = backgoundImage;
		firePropertyChange("backgoundImage", oldValue, this.backgoundImage);
		repaint();
	}
	
	public ImageScale getImageScale() {
		return imageScale;
	}
	
	public void setImageScale(ImageScale backgroundScale) {
		ImageScale oldValue = this.imageScale;
		this.imageScale = backgroundScale;
		firePropertyChange("imageScale", oldValue, this.imageScale);
		repaint();
	}
	
	@Override
	public void paint(Graphics g) {
		if (isVisible() && backgoundImage != null) paintBackground(g);
		super.paint(g);
	}
	
	private void paintBackground(Graphics graphics) {
		Graphics2D g = (Graphics2D) graphics.create();
		
		int outWidth = getWidth();
		int outHeigth = getHeight();
		BufferedImage imageBG = imageScale.getScaleImage(backgoundImage,
				outWidth, outHeigth);
		int inWidth = imageBG.getWidth(); // Ancho de la imagen
		int inHeight = imageBG.getHeight(); // Alto alto de la imagen
		
		int locX, locY;
		
		switch (imageScale) {
		case FILL: { // Centrando horizontalmente.
			locY = 0;
			locX = (outWidth / 2) - (inWidth / 2);
		}
			break;
		case SET: { // Centrando verticalmente.
			locX = 0;
			locY = (outHeigth / 2) - (inHeight / 2);
		}
			break;
		case CENTRE: { // Centrado vertical y horizontalmente
			locX = (outWidth / 2) - (inWidth / 2);
			locY = (outHeigth / 2) - (inHeight / 2);
		}
			break;
		case EXPAND:
		case MOSAIC:
		default:
			// Se estable la misma imagen sin escalar pero se define que esta
			// inicio en (0, 0)
			locX = 0;
			locY = 0;
			break;
		}
		if (isOpaque()) {
			g.setColor(getBackground());
			g.fillRect(0, 0, outWidth, outHeigth);
		}
		g.drawImage(imageBG, locX, locY, getBackground(), this);
	}
}
